package com.smasher.dialog.progress

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager

object ProgressHelper {

    private const val FRAGMENT_TAG_PROGRESS = "FRAGMENT_TAG_PROGRESS"

    fun showProgress(option: ProgressOption, activity: FragmentActivity) {
        showProgress(option, activity.supportFragmentManager)
    }

    fun showProgress(option: ProgressOption, fragment: Fragment) {
        showProgress(option, fragment.childFragmentManager)
    }

    fun showProgress(option: ProgressOption, supportFragmentManager: FragmentManager) {
        var dialog = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_PROGRESS)
        if (dialog == null) {
            dialog = ProgressDialogFragment.newInstance(option)
        }
        if (dialog is ProgressDialogFragment) {
            if (!dialog.isShowing()) {
                dialog.show(supportFragmentManager, FRAGMENT_TAG_PROGRESS)
            }
        }
    }

    fun updateContent(option: ProgressOption, activity: FragmentActivity) {
        updateContent(option, activity.supportFragmentManager)
    }

    fun updateContent(option: ProgressOption, fragment: Fragment) {
        updateContent(option, fragment.childFragmentManager)
    }

    fun updateContent(option: ProgressOption, supportFragmentManager: FragmentManager) {
        var dialog = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_PROGRESS)
        if (dialog == null) {
            dialog = ProgressDialogFragment.newInstance(option)
        }
        if (dialog is ProgressDialogFragment) {
            dialog.setTextOnShown(option.message)
            if (!dialog.isShowing()) {
                dialog.show(supportFragmentManager, FRAGMENT_TAG_PROGRESS)
            }
        }
    }

    fun hideProgress(activity: FragmentActivity) {
        hideProgress(activity.supportFragmentManager)
    }

    fun hideProgress(fragment: Fragment) {
        hideProgress(fragment.childFragmentManager)
    }

    fun hideProgress(supportFragmentManager: FragmentManager) {
        val dialog = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_PROGRESS)
        if (dialog is ProgressDialogFragment) {
            if (dialog.isShowing()) {
                dialog.dismiss()
            }
        }
    }


}